package com.conversationboard.controller;

import java.io.IOException;
import java.sql.SQLException;
import java.util.Date;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.conversationboard.config.Configuration;
import com.conversationboard.controller.debug.ServletDebugInfo;
import com.conversationboard.logger.Logger;
import com.conversationboard.model.Substitutions;
import com.conversationboard.model.User;
import com.conversationboard.security.EncryptedKey;
import com.conversationboard.security.EncryptionException;
import com.conversationboard.site.Site;

@WebServlet(name = "AdminDeleteSubstitutionsControllerServlet", urlPatterns = "/Admin/AdminDeleteSubstitutionsControllerServlet")
public class AdminDeleteSubstitutionsControllerServlet extends HttpServlet {

	private static final long serialVersionUID = -2608707278626887943L;


	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

		request.setCharacterEncoding("UTF-8");
		response.setCharacterEncoding("UTF-8");

		try {
			User user = User.get(request.getUserPrincipal().getName());

			if (!user.isSiteAdmin()) {
				return;
			}

			String key = request.getParameter("key");
			EncryptedKey encryptedKey = new EncryptedKey();

			if (!encryptedKey.isValid(key, user.getLoginId())) {
				Logger.log(new Date(), "Part 1 of error: " + this.getClass().getName(), user);
				String postRequest = ServletDebugInfo.getRawRequest(request);
				Logger.log(new Date(), "Part 2 of error:\n\n" + postRequest, user);
				return;
			}

			String[] toBeDeleted = request.getParameterValues("checkbox");
			Substitutions substitutions = Site.getSubstitutions();

			for (String id : toBeDeleted) {
				substitutions.removeSubstitution(id);
			}

			substitutions.store();

			response.sendRedirect(Configuration.getInstance().getRoot() + "/Pages/Admin/substitutions.jsp");

		} catch (SQLException e) {
			throw new ServletException(e);
		} catch (EncryptionException e) {
			throw new ServletException(e);
		}

	}

}
